package cn.cdeden.knowledge.controller.online.factory.jurisdiction;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.PersonalFilesTree;
import cn.cdeden.knowledge.domain.dto.FilesTree;
import cn.cdeden.knowledge.enums.TreeEnum;
import cn.cdeden.knowledge.enums.TreeTypeEnum;
import cn.cdeden.knowledge.service.PersonalFilesTreeService;
import cn.cdeden.system.api.model.LoginUser;
import com.alibaba.fastjson.JSONObject;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor
@Component("personal")
public class JurisdictionPersonal implements Jurisdiction{

    private final PersonalFilesTreeService filesTreeService;

    @Override
    public JurisdictionResponse getFileJurisdictionDownloadFile(String id, JSONObject jsonObject) throws BadRequestException {
        PersonalFilesTree byId = filesTreeService.getById(id);
        if (ObjectUtils.isEmpty(byId) && !StringUtils.equalsIgnoreCase(TreeTypeEnum.FILE.getType(),byId.getType())){
            throw new BadRequestException("错误的 文件编码 或 不是文件");
        }
        jurisdiction(byId.getCreateId(),byId.getCreateBy(),jsonObject);
        return JurisdictionResponse.success(byId.getStorageId(),byId.getStorageType(),byId.getRealName(),byId.getSuffix());
    }

    @Override
    public JurisdictionResponse getFileDate(String id, JSONObject jsonObject, String userId) throws BadRequestException {
        PersonalFilesTree byId = filesTreeService.getById(id);
        if (ObjectUtils.isEmpty(byId) || !StringUtils.equalsIgnoreCase(TreeTypeEnum.FILE.getType(),byId.getType())){
            throw new BadRequestException("错误的 文件编码 或 不是文件");
        }
        jurisdiction(byId.getCreateId(),byId.getCreateBy(),jsonObject);

        FilesTree tree = MapstructUtils.convert(byId, FilesTree.class);
        tree.setLibraryType(TreeEnum.PERSONAL.getType());

        JurisdictionResponse success = JurisdictionResponse.success(tree);
//        success.setWatermarkTxt("#{[nick_name]}_#{[dept_name]}_#{[phone04]}"); //水印 文件
        return success;
    }


    private boolean jurisdiction(String id, String usernameBy,JSONObject jsonObject) throws BadRequestException {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser(usernameBy); //用户信息
//        FileUserDto user = FileUserUtils.getUser(); //获取当前用户信息
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());
        if (!StringUtils.equalsIgnoreCase(userId,id)){
            throw new BadRequestException("不是编辑人");
        }
        return true;
    }


}
